package com.jiuqi.lr_demo.exception;

import com.jiuqi.lr_demo.utils.Result;
import com.jiuqi.lr_demo.utils.StatusCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<String> handleResourceNotFoundException(Exception e) {
        String exceptionType = e.getClass().getSimpleName();
        log.error("其他异常类型: {}", exceptionType);
        log.error("其他异常信息：{}", e.getMessage());
        return Result.fail("其他异常信息:" + e.getMessage());

    }

    //捕获MissingServletRequestParameterException异常
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("MissingServletRequestParameterException: {}", e.getMessage());
        return Result.fail(StatusCodeEnum.SC400.getCode(), StatusCodeEnum.SC400.getMsg() + "：" + e.getMessage());
    }


    //捕获ArithmeticException异常
    @ExceptionHandler(ArithmeticException.class)
    public Result<String> handleArithmeticException(ArithmeticException e) {
        log.error("ArithmeticException: {}", e.getMessage());
        return Result.fail(StatusCodeEnum.SC500.getCode(), StatusCodeEnum.SC500.getMsg() + "：" + e.getMessage());
    }


    // 捕获NoHandlerFoundException异常，并返回404错误
    @ExceptionHandler(NoResourceFoundException.class)
    public Result<String> handleNoResourceFoundException(NoResourceFoundException e) {
        log.error("NoResourceFoundException: {}", e.getMessage());
        return Result.fail(StatusCodeEnum.SC404.getCode(), StatusCodeEnum.SC404.getMsg() + "：" + e.getMessage());
    }


}

